namespace hjc {

	export class EffectManager extends Singleton implements ILaunchable {

		private static $DEFAULT_PATH = 'resource/skins/effects';
		private static $DEFAULT_BG_COLOR = Color.BLACK;
		private static $DEFAULT_BG_ALPHA = 0.8;
		private $effects: eui.Component[] = [];
		private $skinPath: string;
		private bg: eui.Rect;

		public launch(options: LaunchOptions): EffectManager {
			this.$skinPath = EffectManager.$DEFAULT_PATH;
			this.bg = new eui.Rect();
			this._toggleBg({ bg: false, bgAlpha: EffectManager.$DEFAULT_BG_ALPHA, bgColor: EffectManager.$DEFAULT_BG_COLOR, modal: false, show: false, name: '' });
			// ui.setFull(this.bg, game.layer.effect);
			return this;
		}

		private _build(skin: string, complete: Function): void {
			if (isEmpty(skin)) console.warn('初次调用特效未定义皮肤路径!');
			else {
				let comp = new eui.Component();
				comp.touchEnabled = false;
				comp.touchChildren = false;
				comp.addEventListener(egret.Event.COMPLETE, () => complete(comp), this);
				comp.skinName = `${this.$skinPath}/${skin}.exml`;
			}
		}

		private _toggleBg(te: TEffect): void {
			if (te.bg) {
				this.bg.visible = true;
				if (numeric(te.bgColor)) this.bg.fillColor = te.bgColor;
				if (numeric(te.bgAlpha)) this.bg.alpha = te.bgAlpha;
				this.bg.touchEnabled = te.modal ? true : false;
			} else this.bg.visible = false;

		}

		public playEffect(te: TEffect): void {
			if (isEmpty(game.layer.effect)) {
				console.warn('layer effect not defined ...');
				return;
			}
			let comp: eui.Component = this.$effects[te.name];
			if (te.show) {
				let self = this;
				let next = function (compBuild?: eui.Component) {
					if (compBuild) comp = compBuild;
					self.$effects[te.name] = comp;
					self._toggleBg(te);
					if (isEmpty(te.padding)) ui.setCenter(comp, game.layer.effect);
					else ui.setAlign(comp, te.padding, game.layer.effect);
					te.complete(comp);
				}
				if (comp) next();
				else this._build(te.skin, (comp: eui.Component) => next(comp));
			} else {
				if (comp) ui.remove(comp);
				this.bg.visible = false;
			}
		}
	}
}